import React from 'react';
import { connect } from 'dva';
import { createForm } from 'rc-form';
import cx from 'classnames';
import { WingBlank, WhiteSpace, DatePicker, Picker, InputItem, Flex, List, Button, Toast } from 'antd-mobile';
import { Link, routerRedux } from 'dva/router';
import styles from '../scale/styles.less';
import {SCALE_PRE} from 'const';

Array.prototype.unique2 = function(){
 this.sort(); //先排序
 var res = [this[0]];
 for(var i = 1; i < this.length; i++){
  if(this[i] !== res[res.length - 1]){
   res.push(this[i]);
  }
 }
 return res;
}

function ScalePreTemplate({ dispatch, location, form, scalevalue, detail, ...rest }) {
   
  const { state, query } = location;
  const { type, patientid, step } = location.state;
  const { getFieldProps, getFieldValue, setFieldsValue, validateFields, getFieldError } = form;
  let question = SCALE_PRE[step];

  const isNativeApp = location.pathname.indexOf('/scale_pre') !== -1 && query.s === 'app';

  if (!Object.keys(scalevalue).length) {
    scalevalue = [[], []];
    dispatch({ type: 'scale/save', payload: { scalevalue } });
  }

  let infos = scalevalue[0] || []; //用户信息
  let scores = scalevalue[1] || []; //症状
  for(var z =0;z<scores.length;z++){
     for(var j= z+1; j<scores.length;j++){
      if(scores[z]== scores[j]){
        scores.splice(z,1);
        z--;
      }
     }
  } 

  let nextStep = step + 1;
  const category = step - 2;

  let title = '';
  if (step === 1) {
    title = '完善用户信息';
  }

  let stepQuestions = [];
  if (category >= 0 && category < 5) {
    stepQuestions = SCALE_PRE[category].subject;
    title = SCALE_PRE[category].title;
  }

  const isReturnData = [{ label: '初诊', value: '0' }, { label: '复诊', value: '1' }];

  const validateForm = () => {

    validateFields((err, values) => {
      if (err) {
        const fieldNames = Object.keys(err);
        if (fieldNames[0]) {
          return Toast.fail(getFieldError(fieldNames[0]));
        }
      } else {
        if (step === 1) {
          if (getFieldValue("hy") < getFieldValue("sc")) {
            setFieldsValue({["hy"]: null});
            setFieldsValue({["sc"]: null});
            return Toast.fail("怀孕次数不得小于生产次数", 1);
          }
          const isReturn = getFieldValue('isReturn');
          const height = getFieldValue('height');
          const weight = getFieldValue('weight');
          const hy = getFieldValue('hy');
          const sc = getFieldValue('sc');
          const weeks = getFieldValue('weeks');
          infos = [isReturn, height, weight, hy, sc, weeks];
        }

        if (step > 1) {
          Object.keys(values).forEach((key) => {
            if (values[key]) {
              scores.push(key);
            } 
          });

          // dispatch({ type: 'scale/save', payload: { scalevalue: [infos, scores] } });
        }

        dispatch({ type: 'scale/save', payload: { scalevalue: [infos, scores] } });

        if (nextStep <= 6) {
      
          let pathname = location.pathname;

          // if (isNativeApp) {
          //   pathname = `${location.pathname}?s=${query.s}&doctorid=${query.doctorid}&memberid=${query.memberid}`;
            
          // }
          dispatch(
            routerRedux.replace({
              pathname,
              state: {
                type,
                patientid,
                step: nextStep,
              },
            }),
          );
        } else {
         // 最后一页'提交'
         scores = scores.unique2();
         if(scores.length <= 3){
             Toast.fail('选择的症状信息过少，请重新选择');
         
          }else if(scores.length > 3){
            const patientValue = `${infos[3]}|${infos[4]}|${infos[0]}|${infos[5]}|${infos[1]}|${infos[2]}|${scores.join(',')}`;
            dispatch({
              type: 'scale/submitQuestions',
              payload: {
                // type: query.type || state.type,
                type: 'pre',
                patientId: state.patientid,
                familyId:  state.familyId,
                patientValue,
                ...rest,
              },
            });
          }
        }
      }
    });
  };
  function isDisable(name, value, i){
    if(getFieldValue(2) && name == 1 || getFieldValue(1) && name == 2){
      return true;
    }
    if (scalevalue[1] && scalevalue[1].indexOf("2")!= -1 && name == 1) {
        return true;
    }
    if (scalevalue[1] && scalevalue[1].indexOf("1")!= -1 && name == 2) {
        return true;
    }

    if(getFieldValue(100) && name == 98 || getFieldValue(98) && name == 100){
      return true;
    }
  
    if (scalevalue[1] && scalevalue[1].indexOf("100")!= -1 && name == 98) {
        return true;
    }
    if (scalevalue[1] && scalevalue[1].indexOf("98")!= -1 && name == 100) {
        return true;
    }

    if(getFieldValue(101) && name == 100 || getFieldValue(100) && name == 101){
      return true;
    }
    
    if (scalevalue[1] && scalevalue[1].indexOf("101")!= -1 && name == 100) {
        return true;
    }
    if (scalevalue[1] && scalevalue[1].indexOf("100")!= -1 && name == 101) {
        return true;
    }
    return false;
  }
  function isActive(key, value, i) {
    if (Array.from(scores).find(item => item === key)) {
      return true;
    }

    if (!getFieldValue(key)) {
      return false;
    }

    return getFieldValue(key) === value;
  }

  function handleChange({ target: { type, name, value } }) {
    if (Array.from(scores).find(item => item === name)) {
      setFieldsValue({ [name]: value }); //form实际值与状态不符，用赋值保持相符
      scores = Array.from(scores).filter(item => item !== name); //从scores中去除
    }
    if (getFieldValue(name) === value) {
      setFieldsValue({ [name]: null });
    } else {
      setFieldsValue({ [name]: value });
    }
    if(getFieldValue(2) && name == 1 || getFieldValue(1) && name == 2){
        setFieldsValue({ [name]: null });
    }
    if (scalevalue[1] && scalevalue[1].indexOf("2")!= -1 && name == 1) {
        setFieldsValue({ [name]: null });
    }
    if (scalevalue[1] && scalevalue[1].indexOf("1")!= -1 && name == 2) {
        setFieldsValue({ [name]: null });
    }
    if(getFieldValue(100) && name == 98 || getFieldValue(98) && name == 100){
        setFieldsValue({ [name]: null });
    }
    if (scalevalue[1] && scalevalue[1].indexOf("100")!= -1 && name == 98) {
        setFieldsValue({ [name]: null });
    }
    if (scalevalue[1] && scalevalue[1].indexOf("98")!= -1 && name == 100) {
        setFieldsValue({ [name]: null });
    }
    if(getFieldValue(101) && name == 100 || getFieldValue(100) && name == 101){
        setFieldsValue({ [name]: null });
    }
    if (scalevalue[1] && scalevalue[1].indexOf("101")!= -1 && name == 100) {
        setFieldsValue({ [name]: null });
    }
    if (scalevalue[1] && scalevalue[1].indexOf("100")!= -1 && name == 101) {
        setFieldsValue({ [name]: null });
    }

    dispatch({ type: 'scale/save', payload: { scalevalue: [infos, scores] } });
    
  }
  
  function nextHandler() {
    window.scrollTo(0, 0);
    nextStep = step + 1;
    validateForm();
  }

  function prevHandler() {
    window.scrollTo(0, 0);
    nextStep = step - 1;
    validateForm();
  }

  function submitHandler() {
    nextStep = step + 1;
    validateForm();
  }
  function isBlur(type,value){
    if (type == "height") {
      if (value < 0 || value > 300) {
        setFieldsValue({[type]: null});
        return Toast.fail("请输入正确的身高0~300cm！", 1);
      }
    }
    if (type == "weight") {
      if (value < 20 || value > 200) {
        setFieldsValue({[type]: null});
        return Toast.fail("请输入正确的体重20~200kg！", 1);
      }
    }
    if (type == "weeks") {
      if (value < 2 || value > 50) {
        setFieldsValue({[type]: null});
        return Toast.fail("请输入正确的孕周2~50周！", 1);
      }
    }
    if (type == "hy") {
      if (value < 1) {
        setFieldsValue({[type]: null});
        return Toast.fail("请输入正确的怀孕次数1次以上！", 1);
      }
    }
    if (type == "sc") {
      if (value < 0) {
        setFieldsValue({[type]: null});
        // return Toast.fail("请输入正确的生产次数0次以上！", 1);
      }
    }
  }

  return (
    <WingBlank size="md">
      <WhiteSpace />
      <List>
        <List.Item>
          <Flex justify="center">{`${step}/6 ${title || detail.Title}`}</Flex>
          {step!==1?
            <div>
            <Flex justify="center" style={{marginTop: '0.1rem'}}>您近期（1-2个月）是否出现以下症状</Flex>
            <Flex justify="center">（有即选，无则不选，可以多选）</Flex>
            </div>:""}
        </List.Item>
        {step === 1
          ? /*第1页自定义表单*/
            <div>
              <Picker
                data={isReturnData}
                {...getFieldProps('isReturn', {
                  initialValue: infos[0] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请选择初诊/复诊' }],
                    },
                  ],
                })}
              >
                <List.Item arrow="horizontal">初诊/复诊</List.Item>
              </Picker>
              <InputItem
                {...getFieldProps('height', {
                  initialValue: infos[1] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请输入身高' }],
                    },
                  ],
                  normalize:(v, prev) => {
                    if (v && !/^(([1-9]\d*)|0)(\.\d{0,1}?)?$/.test(v)) {
                      if (v === '.') {
                        return '0.';
                      }
                      return prev;
                    }
                    return v;
                  },
                })}
                placeholder="请输入身高"
                type="digit" 
                onBlur={() => isBlur("height",getFieldValue('height'))}
              >
                身高(cm)
              </InputItem>
              <InputItem
                {...getFieldProps('weight', {
                  initialValue: infos[2] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请输入体重' }],
                    },
                  ],
                  normalize:(v, prev) => {
                    if (v && !/^(([1-9]\d*)|0)(\.\d{0,1}?)?$/.test(v)) {
                      if (v === '.') {
                        return '0.';
                      }
                      return prev;
                    }
                    return v;
                  },
                })}
                placeholder="请输入体重"
                type="digit" 
                onBlur={() => isBlur("weight",getFieldValue('weight'))}
              >
                体重(kg)
              </InputItem>
              <InputItem
                {...getFieldProps('hy', {
                  initialValue: infos[3] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请输入怀孕次数' }],
                    },
                  ],
                })}
                placeholder="请输入怀孕次数"
                type="number"
                onBlur={() => isBlur("hy",getFieldValue('hy'))}
              >
                怀孕次数
              </InputItem>
              <InputItem
                {...getFieldProps('sc', {
                  initialValue: infos[4] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请输入生产次数' }],
                    },
                  ],
                })}
                placeholder="请输入生产次数"
                type="number"
                onBlur={() => isBlur("sc",getFieldValue('sc'))}
              >
                生产次数
              </InputItem>
              <InputItem
                {...getFieldProps('weeks', {
                  initialValue: infos[5] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请输入正确的孕周2~50周' }],
                    },
                  ],
                })}
                placeholder="请输入孕周2~50周"
                type="number"
                onBlur={() => isBlur("weeks",getFieldValue('weeks'))}
              >
                孕周
              </InputItem>
            </div>
          : /*第2-6页动态题目*/
            stepQuestions.map((question, i) => (
              <List.Item wrap multipleLine key={question.id}>
                {`${i + 1}. ${question.title}`}
                <List.Item.Brief>
                  <Flex wrap="wrap" className={styles.questionOptions}>
                    {question.item.map((option, i) => {
                      const key = option.id;
                      const value = option.title;
                      return (
                        <label key={key} className={cx(styles.questionOption, styles.questionOptionNormal, { [styles.questionOptionActive]: isActive(key, value, i),[styles.questionOptionDisable]: isDisable(key, value, i), })}>
                          <input {...getFieldProps(`${key}`)} type="checkbox" name={key} value={value} checked={isActive(key, value, i)} onChange={handleChange} />
                          {value}
                        </label>
                      );
                    })}
                  </Flex>
                </List.Item.Brief>
              </List.Item>
            ))}
        <div>
          <WhiteSpace size="xl" />
          <WingBlank>
            <Flex>
              {step === 1
                ? null
                : <Flex.Item>
                  <Button onClick={prevHandler}>上一页</Button>
                </Flex.Item>}

              {step < 6
                ? <Flex.Item>
                  <Button type="primary" onClick={nextHandler}>下一页</Button>
                </Flex.Item>
                : <Flex.Item>
                  <Button type="primary" onClick={submitHandler}>提交</Button>
                </Flex.Item>}

            </Flex>
          </WingBlank>
          <WhiteSpace size="xl" />
        </div>
      </List>
      <WhiteSpace size="xl" />
    </WingBlank>
  );
}

export default connect(({ scale }) => ({ ...scale }))(createForm()(ScalePreTemplate));
